package org.snail.proxy.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.Enumeration;

public class DSystem {

	private static final Logger LOG = LoggerFactory.getLogger(DSystem.class);

	public static String osname;

	public static int CPU_NUM = 0;
	
	static {
		osname = System.getProperties().getProperty("os.name");
		CPU_NUM = Runtime.getRuntime().availableProcessors();
	}

	public static void sleep(long sleepTime) {
		try {
			Thread.sleep(sleepTime);
		} catch (InterruptedException e) {
			LOG.error("", e);
		}
	}

	public static boolean isWindows() {
		return osname.toLowerCase().startsWith("window");
	}

	public static String getNWIP() throws UnknownHostException {
		InetAddress inet = null;
		LOG.info("当前操作系统 : " + osname);
		if (isWindows()) {
			inet = getWinLocalIp();
			// 针对linux系统
		} else {
			inet = getLinuxLocalIp();
		}
		if (null == inet) {
			throw new UnknownHostException("主机的ip地址未知");
		}

		return inet.getHostAddress().replace("\\", "");// 获得本机IP
	}

	private static InetAddress getWinLocalIp() throws UnknownHostException {
		InetAddress inet = InetAddress.getLocalHost();
		LOG.info("本机的ip=" + inet.getHostAddress());
		return inet;
	}

	private static InetAddress getLinuxLocalIp() {
		Enumeration<NetworkInterface> allNetInterfaces; // 定义网络接口枚举类
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces(); // 获得网络接口

			InetAddress ip = null; // 声明一个InetAddress类型ip地址
			while (allNetInterfaces.hasMoreElements()) // 遍历所有的网络接口
			{
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				LOG.info(netInterface.getName()); // 打印网端名字
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); // 同样再定义网络地址枚举类
				while (addresses.hasMoreElements()) {
					ip = addresses.nextElement();
					LOG.info(ip.getHostAddress());
					if (ip != null && (ip instanceof Inet4Address)) {
						return ip;
					}
				}
			}
		} catch (SocketException e) {
			LOG.error("", e);
		}
		return null;
	}

}
